package com.graduation.alien_yuan.smartmusicplayer;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.MediaStore;
import android.util.Log;

import com.graduation.alien_yuan.smartmusicplayer.bean.MusicModel;
import com.graduation.alien_yuan.smartmusicplayer.utils.LogUtils;
import com.graduation.alien_yuan.smartmusicplayer.utils.Utils;

import java.io.IOException;

public class PlayerService extends Service
{
	private MediaPlayer mPlayer;
	PlayerServiceReceiver playerServiceReceiver;
	private static Uri nowPlayingUri;	//存放当前播放音乐的Uri
	private static String title_of_song;
	private static String artist_of_song;
	private static String album_of_song;
	private static int playmode = 0;				//播放模式
	private static  int currentProgress;		//存放当前音乐进度
	private static  int duration;			//存放音乐文件长度
	public static int currentPosition;
	public UpdateTrack mUpdateTrack;

	@Override
	public IBinder onBind(Intent intent)
	{
		// TODO Auto-generated method stub
		return null;
	}
	@Override
	public void onCreate()
	{
		super.onCreate();
		mPlayer=new MediaPlayer();
		//startUpdateTrack(100);
		playerServiceReceiver =new PlayerServiceReceiver();
		IntentFilter intentFilter=new IntentFilter();
		intentFilter.addAction(ACTION_PLAY_CTRL);
		intentFilter.setPriority(0);
		registerReceiver(playerServiceReceiver, intentFilter);
		LogUtils.d("alien-service:onCreate");

	}

	/**
	 * 反注册广播接收器
	 */
	@Override
	public void onDestroy()
	{
		super.onDestroy();
		unregisterReceiver(playerServiceReceiver);
		Log.d("mLog","service被销毁：onDestroy()被调用");
	}

	public static final String ACTION_PLAY_CTRL = "com.alien.smartmusicplayer.action.CONTROL_ACTION";
	public static final String ACTION_UPDATE_TRACK = "com.alien.smartmusicplayer.action.PLAYER_UPDATE_TRACK";
	public static final String KEY_INTENT_FROM = "KEY_INTENT_FROM";
	public static final String KEY_CTRL_ID = "KEY_CTRL_ID";
	public static final String VALUE_MUSIC_SELECTED = "VALUE_MUSIC_SELECTED";
	public static final String VALUE_CTRL = "VALUE_CTRL";
	public static final String KEY_ID = "KEY_ID";
	public static final String KEY_CURRENT_POSITION = "KEY_CURRENT_POSITION";
	public static final String KEY_PLAY_MODE = "KEY_PLAY_MODE";
	/**
	 * PlayerService广播接收器
	 * 用来接收来自View控件的控制消息，以响应控制信息
	 */
	public class PlayerServiceReceiver extends BroadcastReceiver
	{
		@Override
		public void onReceive(Context context, Intent intent)
		{
			String intentFrom=intent.getStringExtra(KEY_INTENT_FROM);
			//①来自所有歌曲列表的音乐列表项点击
			if (intentFrom.equals(VALUE_MUSIC_SELECTED)){

				currentPosition=intent.getIntExtra(KEY_CURRENT_POSITION, -1);
				playmode=intent.getIntExtra(KEY_PLAY_MODE, playmode);
				nowPlayingUri=Uri.withAppendedPath(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,"/"+String.valueOf(Utils.getMusicModelList(PlayerService.this).get(currentPosition).get_id()));
				/**
				 * （待完成）在这里最好先判断nowPlayingUri是否是音乐文件
				 * 如果不是音乐文件立即返回
				 */
				if (nowPlayingUri != null){
					if (mPlayer.isPlaying())
					{//如果正在播放就先停止和销毁当前播放的音频文件
						mPlayer.stop();
						mPlayer.release();
					}
					Log.d("mLog","点击被接收"+nowPlayingUri);
					//用来接收点击音乐列表项目时，intent传送过来的音乐id					
					mPlayer=createmMediaPlayer(PlayerService.this, nowPlayingUri);
					mPlayer.start();
					duration=mPlayer.getDuration();//获取音乐文件长度
				}

			}//②来自contentfragment的控制台按钮的点击
			else if (intentFrom.equals(VALUE_CTRL)){
				/**
				 * ContentFragmentOnClickListener在ContentFragment.java里
				 * 该intent含有“controlButton”，主要是播放控制按钮:播放、上一曲、下一曲,还有进度条
				 */
				//获取被按下的是哪个按钮
				int controlButton=intent.getIntExtra(KEY_CTRL_ID, -1);
				//播放、上一曲、下一曲   按钮事件处理
				switch (controlButton)
				{
					//暂停/播放
					case R.id.main_play_toggle:

						if (mPlayer.isPlaying()){
							mPlayer.pause();
						}
						else if ( ! mPlayer.isPlaying()){
							mPlayer.start();
						}

						break;
					//上一曲
					case R.id.main_play_previous:
						if (currentPosition == 0){
							currentPosition = Utils.getMusicModelList(getApplicationContext()).size()-1;
						}else {
							currentPosition = currentPosition -1;
						}
						resetMediaPlayer(currentPosition);
						mPlayer.start();
						break;

					//下一曲	
					case R.id.main_play_next:
						currentPosition = (currentPosition+1)% Utils.getMusicModelList(getApplicationContext()).size();
						resetMediaPlayer(currentPosition);
						mPlayer.start();
						break;


					default:
						break;
				}

			}//③来自contentfragment的进度条seek_bar事件处理
			else if (intentFrom.equals("SeekBarChangeListener"))
			{

				int seek_bar=intent.getIntExtra("seek_bar", -1);
				if (seek_bar==R.id.main_play_seekbar)
				{
					int progress=intent.getIntExtra("progress", -1);//获取音乐进度
					mPlayer.seekTo(progress);
					currentProgress=mPlayer.getCurrentPosition();//获取音乐当前播放进度位置
				}
			}//④来自contentMainViewOnClickListener上面的五个按钮的事件处理
			else if (intentFrom.equals("contentMainViewOnClickListener"))
			{
				Log.d("mLog","PlayerService收到来自contentMainViewOnClickListener按钮的广播");
				//获取是由contentMainViewOnClickListener哪个按钮触发的广播
				int mainviewButtonID=intent.getIntExtra("mainviewButtonID", -1);

//				switch (mainviewButtonID)
//				{
//					case R.id.imagebutton_mainview_playmode:
//						playmode=intent.getIntExtra(KEY_PLAY_MODE, playmode);//如果playmode有变化就取intent里带的内容，否则取回原值
//
//						break;
//
//					default:
//						break;
//				}

			}

			/**
			 * 为确保更新准确，要将更新语句放在广播接收器的最后
			 */
			startUpdateTrack(1000);
		}


	}
	/**
	 * 响应了收来自View控件的控制消息后，PlayerService的状态会改变
	 * 定时将PlayerService的新状态通过广播发送出去，让View接收并更新显示内容
	 * ***************************************************************************
	 */
	public class UpdateTrack extends Thread//implements Runnable
	{
		int milliseconds;//更新音轨的间隔时间
		Intent mIntent=new Intent(ACTION_UPDATE_TRACK);
		public UpdateTrack(int ms)
		{
			this.milliseconds=ms;
		}

		@Override
		public  void run()
		{
			//如果mPlayer处于播放状态则更新音轨信息
			while (mPlayer.isPlaying())
			{
				/**
				 * 注意线程安全：下面这句话留在这里会出现线程异常退出，说明log语句留在程序里有可能出问题
				 * //Log.d("UpdateTrack","mPlayer正在播放音乐吗: "+mPlayer.isPlaying());
				 * currentProgress=mPlayer.getCurrentPosition();
				 */

				try
				{
					sleep(milliseconds);
					currentProgress=mPlayer.getCurrentPosition();

					mIntent.putExtra("Uri", nowPlayingUri.toString());
					mIntent.putExtra("isPlaying", mPlayer.isPlaying());			//是否正在播放音乐
					mIntent.putExtra("currentProgress", currentProgress);//存放当前音乐进度					
					mIntent.putExtra("duration", duration);				//存放音乐文件长度

				} catch (Exception e)
				{
					e.printStackTrace();
					Log.d("UpdateTrack","UpdateTrack广播线程异常");
				}

				sendBroadcast(mIntent);

			}
		}

	}

	public void startUpdateTrack(int milliseconds)
	{
		mUpdateTrack=new UpdateTrack(milliseconds);
		mUpdateTrack.start();
	}

	public void resetMediaPlayer(int position){
		LogUtils.d("alien-reset player:"+position);
		if (mPlayer == null){
			mPlayer = createmMediaPlayer(getApplicationContext(),Utils.getMusicModelList(getApplicationContext()).get(position).getUri());
		}else {
			try {
				mPlayer.reset();
				mPlayer.setDataSource(getApplicationContext(),Utils.getMusicModelList(getApplicationContext()).get(position).getUri());
				mPlayer.prepare();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public MediaPlayer createmMediaPlayer(Context context, Uri uri)
	{
		MediaPlayer mp=MediaPlayer.create(context, uri);
		mp.setOnCompletionListener(new mOnCompletionListener());
		return mp;
	}

	/**
	 * 当前歌曲播放完成监听器
	 * @author Administrator
	 *
	 */
	public class mOnCompletionListener implements OnCompletionListener
	{

		@Override
		public void onCompletion(MediaPlayer mp)
		{
			switch (playmode)
			{
				//全部循环
				case 0:								Log.d("mLog", "mOnCompletionListener==>全部循环");
					currentPosition = (currentPosition+1)% Utils.getMusicModelList(getApplicationContext()).size();
					resetMediaPlayer(currentPosition);
					mPlayer.start();
					break;
				//单曲循环
				case 1:								Log.d("mLog", "mOnCompletionListener==>单曲循环");
					mPlayer.start();
					break;
				//随机播放
				case 2:								Log.d("mLog", "mOnCompletionListener==>随机播放");
					currentPosition = (int)Math.random()*Utils.getMusicModelList(getApplicationContext()).size();
					resetMediaPlayer(currentPosition);
					mPlayer.start();
					break;

				default:
					break;
			}

		}

	}


}
